<template>
  <div>
    <div class="steps">
      <el-steps :active="2" finish-status="success" simple>
        <el-step title="询报价信息" />
        <el-step title="定标信息" />
      </el-steps>
    </div>
    <el-card class="product-info purchase_card" shadow="never">
      <el-row slot="header" type="flex" justify="space-between" align="middle">
        <span>定标商品信息</span>
        <div>
          <el-button size="mini" @click="toQuotationPage">重新询价</el-button>
          <el-button size="mini" type="primary" :loading="submitLoading" @click="handleFinishCalibrationOne">定标完成</el-button>
        </div>
      </el-row>
      <!-- :tableHeight="400" -->
      <BasicTable
        ref="multipleTable"
        show-select-col
        :show-pagination="false"
        :show-ActionCol="false"
        :show-total="false"
        :rowHeight="43"
        :tableMaxHeight="600"
        :loading="tableInfo.loading"
        :data-source="tableInfo.list"
        :columns="tableInfo.columns"
        :selection-change="handleSelect"
        @handleRowChange="handleRowChange"
        showSummary
        :summaryMethod="summaryMethod"
      >
        <el-row slot="content_context" class="table-header" v-if="expTypeOptions.length">
          <el-button size="mini" type="primary" :loading="batchBtnLoading" @click="handleBatchEditCause">批量维护异常原因</el-button>
          <el-select size="mini" clearable v-model="priceExpType" placeholder="快速选择">
            <el-option
              v-for="item in expTypeOptions"
              :key="item.priceExpTypeId"
              :label="item.priceExpType"
              :value="item.priceExpTypeId"
              @click.native="handleClickExpType(item)"
            >
            </el-option>
          </el-select>
        </el-row>
      </BasicTable>
    </el-card>
    <!-- 异常类型 -->
    <ApprovalReason
      :reasonVisible.sync="exceptionInfo.visible"
      :expList="exceptionInfo.expList"
      @approvalConfirmCallBack="approvalConfirmCallBack"
    />
    <!-- 超数量1.2倍 -->
    <OverQuantity
      :visible.sync="overQuantityInfo.visible"
      :btnLoading="overQuantityInfo.btnLoading"
      :exceedNumText="overQuantityInfo.exceedNumText"
      :exceedThreeOutText="overQuantityInfo.exceedThreeOutText"
      @handleFinish="handleFinishCalibrationThree"
    />
  </div>
</template>
<script>
import BasicTable from '@/pages/sourcing/components/BasicList';
import ApprovalReason from './components/ApprovalReason';
import OverQuantity from './components/OverQuantity';
import {
  queryCalibrationInfoService,
  checkExceptionTypeService, // 校验异常类型
  checkAmountService, // 校验超1.2倍
  overCalibrationService, // 超1.2倍定标
  queryExpInfoByExpIdService, // 获取异常原因及填写说明
} from '@api/sourcing/selfPurchaseInquiry'
import { toFixedCustomize } from '@/utils/bizUtils'
import { BID_EDIT_COLUMNS, BID_EDIT_DYNAMIC_COLUMNS } from '../constants'

export default {
  // 自进货定标信息
  components: {
    BasicTable,
    ApprovalReason,
    OverQuantity,
  },
  data () {
    return {
      tableInfo: {
        list: [],
        columns: [],
        selection: [],
        loading: false
      },
      // 异常类型勾选
      priceExpType: '',
      selectedExpType: [],
      batchBtnLoading: false,
      // 异常信息
      exceptionInfo: {
        visible: false,
        expList: []
      },
      // 超数量1.2倍
      overQuantityInfo: {
        visible: false,
        btnLoading: false,
        exceedNumText: '',
        exceedNumSkuCodes: [], // 超1.2的商品的集合
        exceedThreeOutText: '',
        exceedThreeOutSkuCodes: [], // 超3个月销量商品集合
      },
      submitLoading: false
    }
  },
  computed: {
    selfPurchaseBillId () {
      return this.$route.query.selfPurchaseBillId
    },
    isCompleteWinBill () {
      return this.$route.query.isCompleteWinBill || 1
    },
    // 异常类型下拉集合
    expTypeOptions () {
      const nestedArray = []
      this.tableInfo.list.map(item => {
        if (item.priceExpTypeList) {
          nestedArray.push(item.priceExpTypeList);
        }
      })
      if (nestedArray.length > 0) {
        let obj = {};
        return nestedArray.flat().reduce((item, next) => {
          if (!obj[next.priceExpTypeId]) {
            obj[next.priceExpTypeId] = true
            item.push(next)
          }
          return item;
        }, [])
      }
      return []
    },
    // 异常类型勾选集合
    selectedExpTypes () {
      const expArr = []
      this.tableInfo.selection.map(item => {
        if (item.priceExpTypeList) {
          expArr.push(item.priceExpTypeList);
        }
      })
      if (expArr.length > 0) {
        let obj = {};
        return expArr.flat().reduce((item, next) => {
          if (!obj[next.priceExpTypeId]) {
            obj[next.priceExpTypeId] = true
            item.push(next)
          }
          return item;
        }, [])
      }
      return []
    }
  },
  mounted () {
    this.queryCalibrationInfo();
  },
  methods: {
    // 表格勾选结果
    handleSelect (val) {
      this.tableInfo.selection = val;
    },
    // 可编辑项联动（中标金额=中标数量*进价）
    handleRowChange (data) {
      const { prop, row, val } = data;
      const propName = prop.split('_')[0];
      const supplierId = prop.split('_')[1];
      if (propName == 'skuNum') {
        row[`skuPrice_${supplierId}`] = toFixedCustomize(row[`unitPrice_${supplierId}`] * val);
      }
    },
    // rows rows数据格式: [{ row: ror(需要显示的行row), selected: true 设置这一行选中与否（selected 为 true 则选中 }]
    // this.$refs.multipleTable.$refs.plTable.toggleRowSelection([{ row: row, selected: true }])
    // 快速选择异常类型
    handleClickExpType (item) {
      this.selectedExpType = [item];
      this.$refs.multipleTable.$refs.plTable.clearSelection()
    },
    // 批量维护异常原因
    handleBatchEditCause () {
      let expTypes = [];
      if (this.tableInfo.selection.length) {
        expTypes = _.cloneDeep(this.selectedExpTypes)
      } else if (this.priceExpType) {
        expTypes = _.cloneDeep(this.selectedExpType)
      }
      if (expTypes.length == 0) {
        return this.$message.warning('请选择要完善异常类型或商品');
      }
      this.queryExpInfoByExpId(expTypes.map(item => item.priceExpTypeId)).then(reasons => {
        if (reasons) {
          expTypes.forEach(ele => {
            ele.concreteExpCauseOptions = reasons[ele.priceExpTypeId];
            ele.fillDesc = '';
          })
          this.exceptionInfo = {
            visible: true,
            expList: expTypes
          }
        }
      })
    },
    // 异常类型信息维护完成
    approvalConfirmCallBack (reasonList) {
      if (this.tableInfo.selection.length) {
        const selectIds = this.tableInfo.selection.map(s => s.selfPurchaseBillDetailsId)
        this.tableInfo.list.forEach(item => {
          if (selectIds.includes(item.selfPurchaseBillDetailsId) && item.priceExpTypeList) {
            item.priceExpTypeList.forEach(i => {
              const filterResult = reasonList.find(ele => ele.priceExpTypeId == i.priceExpTypeId)
              if (filterResult) {
                i.concreteExpCauseId = filterResult.concreteExpCauseId
                i.concreteExpCause = filterResult.concreteExpCause
                i.content = filterResult.content
              }
            })
          }
        })
      } else {
        this.tableInfo.list.forEach(item => {
          item.priceExpTypeList && item.priceExpTypeList.forEach(i => {
            const filterResult = reasonList.find(ele => ele.priceExpTypeId == i.priceExpTypeId)
            if (filterResult) {
              i.concreteExpCauseId = filterResult.concreteExpCauseId
              i.concreteExpCause = filterResult.concreteExpCause
              i.content = filterResult.content
            }
          })
        })
      }
    },
    // 查询异常类型对应原因及填写说明
    async queryExpInfoByExpId (params) {
      const res = await queryExpInfoByExpIdService(params, state => { this.batchBtnLoading = state })
      if (res?.data) {
        return res.data;
      }
      return null
    },
    // 初始化表头
    initTableColumns () {
      this.tableInfo.columns = _.cloneDeep(BID_EDIT_COLUMNS)
    },
    // 获取定标详情
    async queryCalibrationInfo () {
      const params = {
        selfPurchaseBillId: this.selfPurchaseBillId,
        isCompleteWinBill: this.isCompleteWinBill
      }
      const res = await queryCalibrationInfoService(params, state => { this.tableInfo.loading = state })
      if (res) {
        const { skuList } = res.data.winBiddingDto;
        this.initTableData(skuList);
      }
    },
    // 初始化表格数据
    initTableData (skuList) {
      this.tableInfo.list = [];
      this.initTableColumns();
      skuList.forEach((ele, oneIndex) => {
        const curRow = {
          ...ele
        };
        ele.supplierList.forEach((item, index) => {
          this.pushItem(oneIndex, curRow, item, index);
        });
        this.tableInfo.list.push(curRow);
      });
    },
    pushItem (oneIndex, curRow, item, index) {
      // 将行内动态列的信息，平铺到行
      const tag = item.supplierId;
      BID_EDIT_DYNAMIC_COLUMNS.map(item => item.prop).forEach(name => {
        curRow[`${name}_${tag}`] = item[name];
      });
      // 表头，遍历第1行的动态列时，才追加到表头
      if (oneIndex === 0) {
        const children = _.cloneDeep(BID_EDIT_DYNAMIC_COLUMNS)
        children.forEach(i => {
          i.prop = `${i.prop}_${tag}`
        })
        this.tableInfo.columns.push({
          label: item.supplierName,
          prop: item.supplierId,
          children
        });
      }
    },
    // 格式化提交数据
    formatSubmitData () {
      const submitList = [];
      this.tableInfo.list.forEach(ele => {
        ele.supplierList.forEach(item => {
          const tag = item.supplierId;
          item.belongDepartmentName = ele[`belongDepartmentName_${tag}`];
          item.costPrice = ele[`costPrice_${tag}`];
          item.skuNum = ele[`skuNum_${tag}`] || 0;
          item.skuPrice = ele[`skuPrice_${tag}`];
          item.totalPrice = ele[`totalPrice_${tag}`];
          item.workableArrivalTime = ele[`workableArrivalTime_${tag}`];
          item.remark = ele[`remark_${tag}`];
          item.productCenterPrice = ele[`productCenterPrice_${tag}`];
          item.productCenterCostPrice = ele[`productCenterCostPrice_${tag}`];
        });
        const obj = {}
        Object.keys(ele).forEach(i => {
          if (!i.includes('_')) {
            obj[i] = ele[i]
          }
        })
        submitList.push(obj)
      });
      return submitList;
    },
    // 定标完成  校验异常类型
    async handleFinishCalibrationOne () {
      const params = {
        selfPurchaseBillId: this.selfPurchaseBillId,
        skuList: this.formatSubmitData(),
      }
      const res = await checkExceptionTypeService(params, state => { this.submitLoading = state })
      if (res) {
        const { data } = res;
        if (data.hasError) {
          this.$message.error('存在异常类型商品，请完善异常原因')
          this.initTableData(data.skuList);
        } else {
          this.handleFinishCalibrationTwo(res.data)
        }
      }
    },
    // 定标完成 校验是否超1.2倍
    async handleFinishCalibrationTwo (skuInfo) {
      const res = await checkAmountService(skuInfo, state => { this.submitLoading = state })
      if (res) {
        const { data } = res;
        if (data) {
          const {
            exceedNumText = '',
            exceedNumSkuCodes = [],
            exceedThreeOutText = '',
            exceedThreeOutSkuCodes = []
          } = data;
          this.overQuantityInfo = {
            ...skuInfo,
            visible: true,
            btnLoading: false,
            exceedNumSkuCodes, // 超1.2的商品的集合
            exceedNumText, // 超1.2倍要货提示
            exceedThreeOutText, // 超3个月销量提示
            exceedThreeOutSkuCodes, // 超3个月销量商品集合
          }
        } else {
          this.toHomePage()
        }
      }
    },
    // 定标完成 数量超1.2倍定标
    async handleFinishCalibrationThree ({ exceedNumReason, exceedThreeOutReason }) {
      const params = {
        ..._.omit(this.overQuantityInfo, 'visible', 'btnLoading', 'exceedNumText', 'exceedThreeOutText'),
        exceedNumReason, // 超1.2倍要货原因备注
        exceedThreeOutReason, // 超3个月销量原因
      }
      const res = await overCalibrationService(params, state => { this.overQuantityInfo.btnLoading = state })
      if (res) {
        this.overQuantityInfo.visible = false;
        this.toHomePage()
      }
    },
    // 定标完成跳转
    toHomePage () {
      this.$message.success('定标成功')
      this.$router.push({ name: 'selfPurchase' })
    },
    // 重新询价
    toQuotationPage () {
      this.$router.push({ name: 'selfPurchaseQuotationInfo', query: { selfPurchaseBillId: this.selfPurchaseBillId } })
    },
    summaryMethod ({ columns, data }) {
      const means = [] // 合计
      columns.forEach((column, columnIndex) => {
        if (columnIndex === 0) {
          means.push('合计')
        } else if (column.property.includes('skuPrice') || column.property.includes('totalPrice')) {
          const values = data.map(item => Number(item[column.property]));
          // 合计
          if (!values.every(value => isNaN(value))) {
            means[columnIndex] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            means[columnIndex] = '<span style="font-weight: bold;">' + toFixedCustomize(means[columnIndex]) + '元</span>'
          } else {
            means[columnIndex] = '';
          }
        }
      })
      // 返回一个二维数组的表尾合计
      return [means]
    }
  }
};
</script>
<style lang="less" scoped>
.table-header {
  margin-bottom: 5px;
  .el-button {
    margin-right: 3px;
  }
}
.active {
  border: 1px dashed red;
  border-radius: 4px;
  /deep/ input {
    border: none;
  }
}
</style>
